package com.qf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author lyx
 * @date 2022/7/11 21:50
 * redis 分布式锁 加锁  解锁
 */
@Component
public class RedisLockUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 加锁
     * @param key  锁名字
     *
     * @param value    锁的值
     * @param second     锁定时间
     * @return
     */
    public boolean lock(String key,String value,int second){
        return  redisTemplate.opsForValue().setIfAbsent(key,value,second, TimeUnit.SECONDS);
    }

    /**
     * 解锁
     * @param key
     * @return
     */
    public boolean unlock(String key){
        return  redisTemplate.delete(key);
    }


}
